package org.example.myleet.rosalind.revp;

import org.example.myleet.rosalind.utils.FastaReader;

import java.util.HashSet;
import java.util.Set;

public class Solution {

    public static void main(String[] args) {
        Solution solution = new Solution();
        solution.printAllReversePalindrome(">Rosalind_24\n" +
                "TCAATGCATGCGGGTCTATATGCAT\n");
        System.out.println("-----------------");
        solution.printAllReversePalindrome(">Rosalind_5819\n" +
                "CGCGTCTCCTCAGTCCTAAAAGTGAGTGCTATCTGAAGCTAGTCGAGACTCTGCGAGCTG\n" +
                "TTACCCCGATTCAGTAATTTCGAGAATTGCCATTAACACGTAGTACGAGCCGATAGGCGC\n" +
                "TTCGCCCCCAAGATATCACGATCTTCGACCGGAACTCCCGGAATGCTATCTTAGAAAACA\n" +
                "AGTGCCAGATCTTTTATGCCAGCATAAGTCATCAACACAAATATTGCGATAAACATTAAC\n" +
                "CTTGGGAATGGTGCCTCCCAGGATTATCGGCTAAGGGCTGGGGGAGACTGTTGAGGCCCT\n" +
                "CTTGTGGCCACACGGTTGATGTGAAAGCAGCTGGCACAACACCCCAAGCGCAAACGAGTG\n" +
                "AAATCTGCCTGAGGGGTAAACGCAATGAATTTGCAGTGGCTAATTCAGAACGCGGACACC\n" +
                "AGGCTGCAGCCTCCACATAGTAACGCTGAACATGTAACGTAGTACCAGCTGTGTCGGGCG\n" +
                "CTGTGGGCGCCCGGTGGGTGGCGTTTTAGAAGGACAGTGGCCACGCTATTCAGCGCCGCG\n" +
                "GCGGGGTCCCTCATCTTAGGCGGGATCCCTAGCTCAATGGTGGTTAACTAGTCTATCGGG\n" +
                "CTAACGTATCAGAAATACCCACGGTAGACACCGGAGGGTCGGTATTCGAGCATTCCACAA\n" +
                "CAACACATGGAGAGTAACTTGCCGAGTGGATGTCTAGTTAACTGTATTCGTACTTCTGTA\n" +
                "TAGTGTCATAGAGCCAGCATACGGAAAATAGAGATACGAATAGTAGGACGTAAGGAATCG\n" +
                "ACCTGTTAATCCGCACGAGCGCAAGGATTCCTGTGCGGAGGACGATATCGCCGACGGGTG\n" +
                "AAATCCTGGCGC\n");
    }

    public void printAllReversePalindrome(String input) {
        Set<String> res = new HashSet<>();
        String dna = FastaReader.parseFastaInput(input).get(0).getSequence();
        for (int i = 1; i < dna.length() - 2; ++i) {
            if (isComplement(dna.charAt(i), dna.charAt(i + 1))) {
                findReversePalindrome(dna, i - 1, i + 2, res);
            }
        }
        for (String r : res) {
            System.out.println(r);
        }
    }

    private void findReversePalindrome(String dna, int start, int end, Set<String> res) {
        if (isComplement(dna.charAt(start), dna.charAt(end))) {
            int len = end - start + 1;
            if (4 <= len && len <= 12) {
                res.add((start + 1) + " " + len);
            }
            if (0 <= start - 1 && end + 1 < dna.length()) {
                findReversePalindrome(dna, start - 1, end + 1, res);
            }
        }
    }

    private boolean isComplement(char c1, char c2) {
        if (c1 == 'A' && c2 == 'T') {
            return true;
        }
        if (c1 == 'T' && c2 == 'A') {
            return true;
        }
        if (c1 == 'C' && c2 == 'G') {
            return true;
        }
        if (c1 == 'G' && c2 == 'C') {
            return true;
        }
        return false;
    }
}
